package bb.lanxing.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.lib.widget.utils.Density;
import bb.lanxing.util.FileProvider7;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.ImageUtil;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.image.GlideUtils;
import bb.lanxing.util.img.ImageChooserUtil;
import bb.lanxing.util.ui.InputHelper;

public class CommentViewHelper implements View.OnClickListener {
    private static final int REQUEST_IMAGE_FROM_FILE = 61442;
    private static final int REQUEST_IMAGE_FROM_PHOTO = 61441;
    private Activity activity;
    private String atTarget;
    private ViewGroup container;
    private ViewGroup contentContainer;
    private Context context;
    private EditText editInput;
    private boolean enableImage;
    private Fragment fragment;
    private ForegroundColorSpan highLightSpan;
    private String imagePath;
    private FrameLayout imageSelectLayout;
    private View imgAdd;
    private LinearLayout imgContainer;
    private TextView imgCount;
    private ImageView imgSelectView;
    private CommentActionListener listener;
    private List<String> selectedImgs;
    private View sendView;
    private View collapsedView = null;
    private List<String> tempImages = new LinkedList();

    public interface CommentActionListener {
        void onCommentAtRemove();

        void onSend(CharSequence editable, List<String> imageList);
    }

    public CommentViewHelper(Activity activity, CommentActionListener listener, boolean enableImg) {
        this.activity = activity;
        this.context = activity;
        this.listener = listener;
        this.enableImage = enableImg;
        initView(activity.findViewById(R.id.comment_container));
        init();
    }

    public CommentViewHelper(Fragment fragment, View viewGroup, CommentActionListener listener, boolean enableImg) {
        this.fragment = fragment;
        this.context = fragment.getActivity();
        this.listener = listener;
        this.enableImage = enableImg;
        initView(viewGroup.findViewById(R.id.comment_container));
        init();
    }

    private void initView(ViewGroup container) {
        this.container = container;
        this.contentContainer = container.findViewById(R.id.comment_content_container);
        this.imageSelectLayout = container.findViewById(R.id.imageSelectLayout);
        this.imgSelectView = container.findViewById(R.id.comment_img);
        this.editInput = container.findViewById(R.id.comment_edit);
        this.sendView = container.findViewById(R.id.comment_send);
        this.imgCount = container.findViewById(R.id.comment_img_count);
        this.imgContainer = container.findViewById(R.id.comment_img_container);
        this.imgAdd = container.findViewById(R.id.comment_img_add);
    }

    public View addCollapsedView(int layout) {
        View inflate = LayoutInflater.from(this.context).inflate(layout, this.contentContainer, false);
        this.collapsedView = inflate;
        this.contentContainer.addView(inflate);
        if (collapsedView != null) {
            collapsedView.setVisibility(View.VISIBLE);
        }
        return this.collapsedView;
    }

    public View findCollapsedView(int id) {
        View view = this.collapsedView;
        if (view == null) {
            return null;
        }
        return view.findViewById(id);
    }

    private void init() {
        this.sendView.setOnClickListener(this);
        this.imgSelectView.setOnClickListener(this);
        this.imgAdd.setOnClickListener(this);
        this.selectedImgs = new LinkedList<>();
        // TODO: 2024/6/26 hide add image for comment
//        this.imgSelectView.setVisibility(this.enableImage ? View.VISIBLE : View.GONE);
        View view = this.collapsedView;
        if (view != null) {
            view.setVisibility(View.VISIBLE);
            this.imageSelectLayout.setVisibility(View.GONE);
        }
        this.editInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (CommentViewHelper.this.atTarget == null || after != 0) {
                    return;
                }
                CommentViewHelper commentViewHelper = CommentViewHelper.this;
                if (start < commentViewHelper.buildAtTo(commentViewHelper.atTarget).length()) {
                    CommentViewHelper.this.removeAtTo();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                CharSequence input = CommentViewHelper.this.getInput();
                if (CommentViewHelper.this.atTarget != null) {
                    CommentViewHelper commentViewHelper = CommentViewHelper.this;
                    input = TextUtils.replace(input, new String[]{commentViewHelper.buildAtTo(commentViewHelper.atTarget)}, new String[]{""});
                }
                CommentViewHelper.this.sendView.setEnabled(!TextUtils.isEmpty(input));
            }
        });
        this.container.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            int i = oldTop - top;
            int dp2px = Density.dp2px(CommentViewHelper.this.context, 100.0f);
            if (i <= dp2px) {
                if (i < (-dp2px)) {
                    CommentViewHelper.this.sendView.setVisibility((!TextUtils.isEmpty(CommentViewHelper.this.getInput()) || CommentViewHelper.this.imgContainer.getVisibility() == View.VISIBLE) ? View.VISIBLE : View.GONE);
                    if (CommentViewHelper.this.collapsedView != null && CommentViewHelper.this.imgContainer.getVisibility() != View.VISIBLE && CommentViewHelper.this.sendView.getVisibility() != View.VISIBLE) {
                        CommentViewHelper.this.collapsedView.setVisibility(View.VISIBLE);
                        CommentViewHelper.this.imageSelectLayout.setVisibility(View.GONE);
                    }
                    CommentViewHelper.this.editInput.getParent().requestLayout();
                    return;
                }
                return;
            }
            if (CommentViewHelper.this.enableImage && CommentViewHelper.this.imgContainer.getVisibility() == View.VISIBLE) {
                CommentViewHelper.this.imgContainer.setVisibility(View.GONE);
                CommentViewHelper.this.imgContainer.getParent().requestLayout();
            }
            CommentViewHelper.this.sendView.setVisibility(View.VISIBLE);
            if (CommentViewHelper.this.collapsedView != null && CommentViewHelper.this.collapsedView.getVisibility() == View.VISIBLE) {
                CommentViewHelper.this.collapsedView.setVisibility(View.GONE);
                CommentViewHelper.this.imageSelectLayout.setVisibility(View.VISIBLE);
            }
            CommentViewHelper.this.editInput.getParent().requestLayout();
        });
        this.editInput.setOnEditorActionListener((v, actionId, event) -> {
            if (4 != actionId || TextUtils.isEmpty(CommentViewHelper.this.editInput.getEditableText())) {
                return false;
            }
            CommentViewHelper commentViewHelper = CommentViewHelper.this;
            commentViewHelper.onClick(commentViewHelper.sendView);
            return true;
        });
    }

    public String buildAtTo(String atTo) {
        return this.context.getString(R.string.topic_post_reply_to, atTo) + " ";
    }

    public void commentAt(String newTarget) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(this.editInput.getText());
        String buildAtTo = buildAtTo(newTarget);
        int length = (buildAtTo.length() - newTarget.length()) - 1;
        String str = this.atTarget;
        if (str != null) {
            spannableStringBuilder.replace(0, buildAtTo(str).length(), buildAtTo);
        } else {
            spannableStringBuilder.insert(0, buildAtTo);
        }
        this.atTarget = newTarget;
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(this.context.getResources().getColor(R.color.global_blue_color));
        this.highLightSpan = foregroundColorSpan;
        spannableStringBuilder.setSpan(foregroundColorSpan, length, buildAtTo.length(), 33);
        this.editInput.setText(spannableStringBuilder);
        this.editInput.setSelection(spannableStringBuilder.length());
        InputHelper.showSoftInput(this.editInput);
    }

    public void removeAtTo() {
        String str = this.atTarget;
        if (str == null) {
            return;
        }
        String buildAtTo = buildAtTo(str);
        String obj = this.editInput.getText().toString();
        if (obj.contains(buildAtTo)) {
            this.atTarget = null;
            this.editInput.setText(obj.replace(buildAtTo, "").trim());
            if (this.highLightSpan != null) {
                this.editInput.getText().removeSpan(this.highLightSpan);
                this.highLightSpan = null;
            }
            EditText editText = this.editInput;
            editText.setSelection(editText.getText().length());
        }
        if (listener != null) {
            listener.onCommentAtRemove();
        }
    }

    @Override
    public void onClick(View v) {
        int itemId = v.getId();

        if (R.id.comment_img == itemId) {
            if (this.imgContainer.getVisibility() == View.VISIBLE) {
                this.imgContainer.setVisibility(View.GONE);
                if (this.editInput.hasFocus()) {
                    InputHelper.showSoftInput(this.editInput);
                    return;
                } else {
                    this.sendView.setVisibility(View.GONE);
                    return;
                }
            }
            this.sendView.setVisibility(View.VISIBLE);
            this.imgContainer.setVisibility(View.VISIBLE);
            InputHelper.hideSoftInput(this.editInput);
            View view = this.collapsedView;
            if (view == null || view.getVisibility() != View.VISIBLE) {
                return;
            }
            this.collapsedView.setVisibility(View.GONE);
        } else if (R.id.comment_img_add == itemId) {
            if (this.fragment == null && this.activity == null) {
                return;
            }
            addImage();
        } else if (R.id.comment_send == itemId) {
            if (App.getContext().getSigninUser().getLevel() < 2) {
                Toast.makeText(this.context, "您的等级过低无法发布。快去记录运动吧，升级到 LV2 就可发布啦!", Toast.LENGTH_SHORT).show();
                return;
            }
            CharSequence input = getInput();
            String str = this.atTarget;
            if (str != null) {
                input = TextUtils.replace(input, new String[]{buildAtTo(str)}, new String[]{""});
            }
            if (TextUtils.isEmpty(input)) {
                return;
            }
            if (listener != null) {
                listener.onSend(input, this.enableImage ? this.selectedImgs : null);
            }

            this.editInput.setText("");
            InputHelper.hideSoftInput(this.editInput);
            if (this.enableImage) {
                this.tempImages.removeAll(this.selectedImgs);
                this.selectedImgs.clear();
                notifyImages();
                if (this.imgContainer.getVisibility() == View.VISIBLE) {
                    this.imgContainer.setVisibility(View.GONE);
                }
            }
            this.sendView.setVisibility(View.GONE);
            View view2 = this.collapsedView;
            if (view2 == null || view2.getVisibility() == View.VISIBLE) {
                return;
            }
            this.collapsedView.setVisibility(View.VISIBLE);
        }
    }

    private void addImage() {
        if (!AppFileUtils.isSdCardAvailable()) {
            App.getContext().showMessage(R.string.sdcard_null);
            return;
        }
        final File buildTakePhotoDir = ImageUtil.buildTakePhotoDir();
        if (buildTakePhotoDir == null) {
            return;
        }
        new BiciAlertDialogBuilder(this.context).setTitle(R.string.dialog_choose_image).setItems(new CharSequence[]{this.context.getString(R.string.dialog_take_photo), this.context.getString(R.string.dialog_photo_album)}, (dialog, which) -> {
            if (which == 0) {
                RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getCameraPermission()).permissionRequestEachCombined(CommentViewHelper.this.fragment != null ? CommentViewHelper.this.fragment.getActivity() : (FragmentActivity) CommentViewHelper.this.activity, new RxPermissionUtil.PermissionCallBack() {
                    @Override
                    public void deny() {
                    }

                    @Override
                    public void granted() {
                        if (!App.isManagersInit) {
                            App.getContext().initManagersWithPermissions();
                        }
                        File file2 = new File(buildTakePhotoDir, File.separator + System.currentTimeMillis() + ".jpg");
                        CommentViewHelper.this.imagePath = file2.getAbsolutePath();
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra("output", FileProvider7.getUriForFile(CommentViewHelper.this.fragment != null ? CommentViewHelper.this.fragment.getActivity() : CommentViewHelper.this.activity, file2));
                        if (intent.resolveActivity(CommentViewHelper.this.context.getPackageManager()) != null) {
                            if (CommentViewHelper.this.fragment != null) {
                                CommentViewHelper.this.fragment.startActivityForResult(intent, CommentViewHelper.REQUEST_IMAGE_FROM_PHOTO);
                                return;
                            } else if (CommentViewHelper.this.activity != null) {
                                CommentViewHelper.this.activity.startActivityForResult(intent, CommentViewHelper.REQUEST_IMAGE_FROM_PHOTO);
                                return;
                            } else {
                                return;
                            }
                        }
                        App.getContext().showMessage(R.string.toast_find_no_image_app);
                    }
                });
            } else if (which == 1) {
                if (CommentViewHelper.this.fragment != null) {
                    ImageChooserUtil.startChooser(CommentViewHelper.this.fragment, 9, new ArrayList<>(CommentViewHelper.this.selectedImgs), CommentViewHelper.REQUEST_IMAGE_FROM_FILE);
                } else if (CommentViewHelper.this.activity != null) {
                    ImageChooserUtil.startChooser(CommentViewHelper.this.activity, 9, new ArrayList<>(CommentViewHelper.this.selectedImgs), CommentViewHelper.REQUEST_IMAGE_FROM_FILE);
                }
            }
        }).show();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == REQUEST_IMAGE_FROM_FILE) {
                this.selectedImgs.clear();
                this.selectedImgs.addAll(ImageChooserUtil.getSelectedImagePath(data));
                notifyImages();
            } else if (requestCode == REQUEST_IMAGE_FROM_PHOTO) {
                this.selectedImgs.add(this.imagePath);
                this.tempImages.add(this.imagePath);
                notifyImages();
                this.imagePath = null;
            }
        }
    }

    private void notifyImages() {
        LinearLayout linearLayout = this.imgContainer;
        linearLayout.removeViews(0, linearLayout.getChildCount() - 1);
        for (int i = 0; i < this.selectedImgs.size(); i++) {
            ImageView imageView = (ImageView) LayoutInflater.from(this.imgContainer.getContext()).inflate(R.layout.channel_topic_add_photo_item, this.imgContainer, false);
            this.imgContainer.addView(imageView, i);
            imageView.setTag(i);
            GlideUtils.Companion companion = GlideUtils.companion;
            Context context = imageView.getContext();
            companion.loadImage(context, "file://" + this.selectedImgs.get(i), imageView, R.drawable.ic_img_avatar_team, R.drawable.ic_img_avatar_team);
            imageView.setOnClickListener(view -> CommentViewHelper.this.showDeleteOption((ImageView) view, (Integer) view.getTag()));
        }
        int size = this.selectedImgs.size();
        if (size == 0) {
            this.imgCount.setVisibility(View.GONE);
            this.imgSelectView.setImageResource(R.drawable.ic_default);
            return;
        }
        if (this.selectedImgs.size() == 9) {
            this.imgAdd.setVisibility(View.GONE);
        }
        this.imgCount.setVisibility(View.VISIBLE);
        this.imgCount.setText(String.valueOf(size));
        this.imgSelectView.setImageResource(R.drawable.ic_default);
    }

    public void showDeleteOption(final ImageView imageView, final int tag) {
        PopupMenu popupMenu = new PopupMenu(this.imgContainer.getContext(), imageView);
        popupMenu.inflate(R.menu.menu_image_delete);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(item -> {
            imageView.setVisibility(View.GONE);
            CommentViewHelper.this.imgAdd.setVisibility(View.VISIBLE);
            CommentViewHelper.this.imgContainer.removeViewAt(tag);
            CommentViewHelper.this.selectedImgs.remove(tag);
            for (int i = tag; i < CommentViewHelper.this.imgContainer.getChildCount() - 1; i++) {
                ImageView imageView2 = CommentViewHelper.this.imgContainer.getChildAt(i).findViewById(R.id.photoTopic);
                imageView2.setTag((Integer) imageView2.getTag() - 1);
            }
            int size = CommentViewHelper.this.selectedImgs.size();
            if (size == 0) {
                CommentViewHelper.this.imgCount.setVisibility(View.GONE);
                CommentViewHelper.this.imgSelectView.setImageResource(R.drawable.ic_default);
            } else if (CommentViewHelper.this.selectedImgs.size() == 9) {
                CommentViewHelper.this.imgCount.setText(String.valueOf(size));
                CommentViewHelper.this.imgCount.setVisibility(View.VISIBLE);
                CommentViewHelper.this.imgSelectView.setImageResource(R.drawable.ic_default);
            }
            return true;
        });
    }

    public Editable getInput() {
        EditText editText = this.editInput;
        if (editText == null) {
            return null;
        }
        return editText.getText();
    }

    public List<String> getImages() {
        return this.selectedImgs;
    }

    public void deleteTemp() {
        for (String str : this.tempImages) {
            File file = new File(str);
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
